<?php namespace App\Http\Controllers\Api;

use App\AiRecord;
use App\Content;
use App\ContentXUser;
use App\Files;
use App\Http\Controllers\Controller;
use App\Http\Services\AiManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Images;
use App\User;
use Faker\Provider\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AiController extends Controller
{
    public function getAiDiagnose(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $imageId = $request->get("img_id");

        $thatImage = Images::whereId($imageId)->first();

        if(!$thatImage)
            return response()->json(["level"=>"error","message"=>"图片不存在"]);

        $thatFile = Files::whereId($thatImage->file_id)->first();
        if(!$thatFile)
            return response()->json(["level"=>"error","message"=>"文件不存在"]);

        $result = AiManager::aiDiagnose($thatFile);

//        Log::error("aaaaaaaaaaaaaa=>".print_r($result,true));

        if(isset($result->code) && $result->code == "40001"){
            $data = $result->data;

            $newAiRecord = new AiRecord();
//            $newAiRecord->score   = rand(60,90);
            $newAiRecord->user_id = $user->id;
            $newAiRecord->img_id  = $imageId;
            $newAiRecord->feel    = "【非医学确诊，仅作参考】".$data->feel;
            $newAiRecord->recomand = $data->recomand;
            $newAiRecord->typeName = $data->typeName;
            $newAiRecord->filepath = $data->filepath;
            $newAiRecord->typeConfidence = $data->typeConfidence;
            $newAiRecord->shemianName = $data->shemianName;
            $newAiRecord->shemianDesc = $data->shemianDesc;
            $newAiRecord->shemianConfidence = $data->shemianConfidence;
            $newAiRecord->shexinName        = $data->shexinName;
            $newAiRecord->shexinDesc        = $data->shexinDesc;
            $newAiRecord->shexinConfidence  = $data->shexinConfidence;
            $newAiRecord->taiseName = $data->taiseName;
            $newAiRecord->taiseDesc = $data->taiseDesc;
            $newAiRecord->taiseConfidence = $data->taiseConfidence;
            $newAiRecord->taizhiName = $data->taizhiName;
            $newAiRecord->taizhiDesc = $data->taizhiDesc;
            $newAiRecord->taizhiConfidence = $data->taizhiConfidence;
//            $newAiRecord->createTime = $data->createTime;
//            $newAiRecord->uid = $data->uid;
            $newAiRecord->xleftBottom = $data->xleftBottom;
            $newAiRecord->yleftBottom = $data->yleftBottom;
            $newAiRecord->xrightTop = $data->xrightTop;
            $newAiRecord->yrightTop = $data->yrightTop;
            $newAiRecord->save();

            $newAiRecord->score = AiManager::getAiScore($newAiRecord);

            $newAiRecord->save();

            $newAiRecord->filepath = FileManager::getImgUrl($newAiRecord->img_id);

            return response()->json(["level"=>"success","message"=>"检测成功","data"=>$newAiRecord]);
        }else{
            return response()->json(["level"=>"error","message"=>"没识别到舌头哦！请再靠近一些，舌头在虚线内哦！"]);
        }
    }

    public function getLastDiagnose(Request $request){
        $id = $request->get("id");

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(["level"=>"success","message"=>"获取成功","data"=>[]]);

        if(!is_null($id) && trim($id) != ''){
            $myDiagnose = AiRecord::whereUserId($user->id)->whereId($id)->first();
        }else{
            $myDiagnose = AiRecord::whereUserId($user->id)->orderBy("id","desc")->first();
        }

        if($myDiagnose){
            if($myDiagnose->score <= 20){
                $myDiagnose->feel = "【非医学确诊，仅作参考】一级 表皮（皮肤炎症）皮炎、湿疹、皮肤油腻、毛囊炎、皮肤瘙痒、皮肤过敏、长痘长斑、牛皮藓、白癜风";
            }elseif ($myDiagnose->score > 20 && $myDiagnose->score <= 40){
                $myDiagnose->feel = "【非医学确诊，仅作参考】二级 肌肉（酸、困、累、乏）肌肉酸困、疲累、腰背酸软、四肢乏力、肩颈肥厚、关节酸困";
            }elseif ($myDiagnose->score > 40 && $myDiagnose->score <= 60){
                $myDiagnose->feel = "【非医学确诊，仅作参考】三级 骨骼（肩周、颈椎）四肢关节疼痛、肩颈酸痛、肩周炎、腰酸背痛、颈椎病、腰间盘突出、关节彭出、滑脱、风湿性关节炎、变天关节痛、乳腺增生、结节、盗汗";
            }elseif ($myDiagnose->score > 60 && $myDiagnose->score <= 80){
                $myDiagnose->feel = "【非医学确诊，仅作参考】四级 脏腑（妇科、脾胃、肺）囊肿、胃炎、肺部疾病、肌瘤、阳痿、早泄、痛风、三高、经常腹痛腹泻、大便不成形、常年手脚冰冷、浮肿、眼袋、反复口腔溃疡、口臭、食欲不振、消化不良、头发油腻、脱发、血脂血糖偏高、男妇科疾病、痛经、宫寒";
            }else{
                $myDiagnose->feel = "【非医学确诊，仅作参考】五级 全身细胞（肿瘤）肿瘤及癌症、切了又长，长了又切";
            }
            $myDiagnose->score = $myDiagnose->score . "%";
            $myDiagnose->filepath = FileManager::getImgUrl($myDiagnose->img_id);
        }else{
            return response()->json(["level"=>"error","message"=>"您还未进行检测或检测内容不存在"]);
        }

        $mycontentIds = ContentXUser::whereAiRecordId($myDiagnose->id)->pluck("content_id")->toArray();
        $contents = Content::whereIn("id",$mycontentIds)->get();

        $myDiagnose->content_list = $contents;



        return response()->json(["level"=>"success","message"=>"检测成功","data"=>$myDiagnose]);
    }

    public function getMyDiagnose(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page  = $request->get("page",1);
        $limit = $request->get("limit",5);

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;

        $myDiagnoses = AiRecord::whereUserId($user->id)->offset($page * $limit)->limit($limit)->orderBy("id","desc")->get();
        if(count($myDiagnoses) > 0){
            foreach ($myDiagnoses as $myDiagnose){
                $myDiagnose->score_str    = $myDiagnose->score . "%";
                $myDiagnose->filepath = FileManager::getImgUrl($myDiagnose->img_id);
            }
        }

        $page_info['total']=AiRecord::whereUserId($user->id)->count();

        return response()->json(["level"=>"success","message"=>"检测成功","data"=>$myDiagnoses,'page_info' => $page_info]);
    }

    public function getShopInfo(Request $request){
        $shopName = "十二合中医除寒祛湿体验馆";
        $shopAddress = "广东省深圳市南山区后海粤海创业路西海湾花园2099-32";
        $shopOpenTime = "10:00-20:00";
        $shopLat = "22.5142";
        $shopLng = "113.931";

        $result = [
            "shop_name"=>$shopName,
            "shop_address"=>$shopAddress,
            "shop_open_time"=>$shopOpenTime,
            "shop_lat"=>$shopLat,
            "shop_lng"=>$shopLng
        ];
        return response()->json(["level"=>"success","message"=>"检测成功","data"=>$result]);
    }
}
